package Controller

import (
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"jxc/Common"
	"strconv"
	"time"
)

func UserInfo(ctx *gin.Context) {
	Common.RetMsg(1, "SUCCESS", gin.H{"token": "112233"}, ctx)
}
func Login(ctx *gin.Context) {

	data := ctx.PostForm("data")
	signature := ctx.PostForm("signature")
	fmt.Println(signature)
	if data == "" {
		Common.RetMsg(0, "data is null", nil, ctx)
		return
	}
	if !SignatureValidation(data, signature) {
		Common.RetMsg(0, "signature error", nil, ctx)
		return
	}
	dataStr, deErr := base64.StdEncoding.DecodeString(data)
	if deErr != nil {
		Common.RetMsg(0, "Server Error", nil, ctx)
		return
	}
	dataJson := Common.Login{}
	err := json.Unmarshal(dataStr, &dataJson)
	if err != nil {
		return
	}
	timestamp := time.Now().Unix() - dataJson.Timestamp
	if timestamp < -30 || timestamp > 30 {
		Common.RetMsg(0, "time out "+strconv.FormatInt(timestamp, 10), nil, ctx)
		return
	}
	if len(dataJson.Username) != 11 {
		Common.RetMsg(0, "account must 11 length", nil, ctx)
		return
	}
	if len(dataJson.Password) < 6 || len(dataJson.Password) > 16 {
		Common.RetMsg(0, "6 < password length < 16", nil, ctx)
		return
	}
	db := Common.GetDB()
	admin := Common.Admin{}
	if db.First(&admin, "Account = ?", dataJson.Username).RowsAffected == 0 {
		Common.RetMsg(0, "account error", nil, ctx)
		return
	}
	h := md5.New()
	h.Write([]byte("jxc" + dataJson.Password))
	password := hex.EncodeToString(h.Sum(nil))
	if admin.Password != password {
		Common.RetMsg(0, "password error", nil, ctx)
		return
	}
	token, toErr := Common.ReleaseToken(admin)
	if toErr != nil {
		Common.RetMsg(0, "500 Internal Server Error", nil, ctx)
		return
	}
	Common.RetMsg(1, "SUCCESS", gin.H{"token": token}, ctx)
}

func SignatureValidation(data, signature string) bool {
	h := md5.New()
	h.Write([]byte(data + viper.GetString("server.token")))
	tokenRe := hex.EncodeToString(h.Sum(nil))
	if signature == tokenRe {
		return true
	}
	return false
}
